//
//  BattleActionLayer.cpp
//  airfight
//
//  Created by aaron more on 12-8-21.
//  Copyright (c) 2012年 moonriver. All rights reserved.
//

#include <iostream>
#include <math.h>
#include "BattleActionLayer.h"
#include "FighterPrototypes.h"
#include "Fighter.h"
#include "Bullet.h"
#include "EnemyPrototypes.h"
#include "Enemy.h"
#include "StagePrototypes.h"
#include "StageEnemy.h"
#include "TracePrototypes.h"
#include "Trace.h"
#include "CCActionIntervalEx.h"
#include "ActionManager.h"
#include "MsgBoxLayer.h"
#include "MenuLayer.h"

//#define BOXTEST


static b2Vec2 toMeters(CCPoint pPoint)
{
    return b2Vec2(pPoint.x/PTM_RATIO,pPoint.y/PTM_RATIO);
}

static CCPoint toPixels(b2Vec2 vec)
{
    return ccpMult(CCPointMake(vec.x,vec.y), PTM_RATIO);
}

BattleActionLayer* BattleActionLayer::m_pInstance = NULL;

BattleActionLayer::BattleActionLayer() 
: m_iElapseFrame(0)
,m_bPaused(false)
,frontGround(NULL)
,rearGround(NULL)
,frontGround_rollingSpeed(0)
,rearGround_rollingSpeed(0)
,stage(NULL)
,playerFullBlood(0)
{
    bonusDict = CCDictionary::create();
    bonusDict->retain();
}

BattleActionLayer::~BattleActionLayer()
{
    BattleActionLayer::getInstance()->m_pInstance = NULL;

    delete m_World;
    m_World = NULL;
    delete m_debugDraw;
    m_debugDraw = NULL;
//    CC_SAFE_RELEASE(frontGround);
//    CC_SAFE_RELEASE(rearGround);
//    CC_SAFE_RELEASE(stage);
    
//    m_SpriteFrameCache->removeUnusedSpriteFrames();
//    CCTextureCache::sharedTextureCache()->removeUnusedTextures();
//    m_SpriteFrameCache->purgeSharedSpriteFrameCache();
}

bool BattleActionLayer::init(/*CCDictionary *p_params*/)
{
    DBManager* dbManager = DBManager::getInstance();

    dbManager->getPlayerInfo(new CCObject());
    dbManager->closeDB();
    
    screenSize = CCDirector::sharedDirector()->getWinSize();
    int fighterID = 1; //((CCInteger*)p_params->objectForKey("fighterid"))->getValue();
    int stageID = 1; //((CCInteger*)p_params->objectForKey("stageid"))->getValue();
    m_SpriteFrameCache = CCSpriteFrameCache::sharedSpriteFrameCache();  
    m_SpriteFrameCache->addSpriteFramesWithFile("airfight.plist","airfight.png");
    m_SpriteBatch = CCSpriteBatchNode::create("airfight.png");
    
    stage = StagePrototypes::getInstance()->getStageByID(stageID);
    initBackground();
    initWorld();
    initPauseButton();
    initPlayerFighter(fighterID);
    initLifeBar();
    
    return true;
}

void BattleActionLayer::initBackground()
{ 
#ifndef BOXTEST
    Background *front = stage->getFrontBackground();
    frontGround_rollingSpeed = front->getSpeed();
    frontGround = CCSprite::create(front->getRes().c_str(),CCRectMake(0, 0, screenSize.width, screenSize.height));
    frontGroundRe = CCSprite::create(front->getRes().c_str(),CCRectMake(0, 0, screenSize.width, screenSize.height));
    frontGround->setAnchorPoint(CCPointZero);
    frontGroundRe->setAnchorPoint(CCPointZero);
    frontGround->setPosition(ccp(0,0));
    frontGroundRe->setPosition(ccp(0, 480));  //暂时写死高度
    
    
    Background *rear = stage->getRearBackground();
    rearGround_rollingSpeed = rear->getSpeed();
    rearGround = CCSprite::create(rear->getRes().c_str(),CCRectMake(0, 0, screenSize.width, screenSize.height));
    rearGroundRe = CCSprite::create(rear->getRes().c_str(),CCRectMake(0, 0, screenSize.width, screenSize.height));
    rearGround->setAnchorPoint(CCPointZero);
    rearGroundRe->setAnchorPoint(CCPointZero);
    rearGround->setPosition(ccp(0,0));
    rearGroundRe->setPosition(ccp(0, 480));//暂时写死高度
#endif
    //float backgroundheight = background1->getContentSize().height;
    
}

void BattleActionLayer::initWorld()
{
    b2Vec2 gravity;
    gravity.Set(0.0f, 0.0f);
    m_World = new b2World(gravity);
    
    m_debugDraw = new GLESDebugDraw( PTM_RATIO );
    m_World->SetDebugDraw(m_debugDraw);
    
    uint32 flags = 0;
    flags += b2Draw::e_shapeBit;
    flags += b2Draw::e_jointBit;
    flags += b2Draw::e_aabbBit;
    flags += b2Draw::e_pairBit;
    flags += b2Draw::e_centerOfMassBit;
    m_debugDraw->SetFlags(flags);
    
    m_World->SetAllowSleeping(false);
    m_World->SetContinuousPhysics(true);

    m_Listener = new CollisionListener();
    //m_World->SetContactFilter(b2ContactFilter *filter); //可以自己定义碰撞规则
    m_World->SetContactListener(m_Listener);
   
    /*float widthInMeters = screenSize.width / PTM_RATIO;
    float heightInMeters = screenSize.height / PTM_RATIO;
    
    b2Vec2 lowerLeftCorner = b2Vec2(0,0);
    b2Vec2 lowerRightCorner = b2Vec2(widthInMeters,0);
    b2Vec2 upperLeftCorner = b2Vec2(0,heightInMeters);
    b2Vec2 upperRightCorner = b2Vec2(widthInMeters,heightInMeters);
    
    int density = 0;
    
    // Define the ground body.
    b2BodyDef groundBodyDef;
    groundBodyDef.position.Set(0, 0); // bottom-left corner

    b2Body* groundBody = m_World->CreateBody(&groundBodyDef);
    
    // Define the ground box shape.
    b2EdgeShape groundBox;
    
    // bottom    
    groundBox.Set(lowerLeftCorner, lowerRightCorner);
    groundBody->CreateFixture(&groundBox,density);
    
    // top
    groundBox.Set(upperLeftCorner, upperRightCorner);
    groundBody->CreateFixture(&groundBox,density);
    
    // left
    groundBox.Set(upperLeftCorner, lowerLeftCorner);
    groundBody->CreateFixture(&groundBox,density);
    
    // right
    groundBox.Set(upperRightCorner, lowerRightCorner);
    groundBody->CreateFixture(&groundBox,density);*/

}

void BattleActionLayer::initLifeBar()
{
    m_LifeBar = CCSprite::create();
    m_LifeBar->initWithSpriteFrameName("life_bar.png");
    
    m_LifeBarBack = CCSprite::create();
    m_LifeBarBack->initWithSpriteFrameName("life_bar_back.png");
    m_LifeBarBack->setAnchorPoint(ccp(0,0));
    m_LifeBarBack->setPosition(ccp(0,450));
    m_LifeBarBack->setScale(0.5);
    
    m_LifeProgress = CCProgressTimer::create(m_LifeBar);
    m_LifeProgress->setType(kCCProgressTimerTypeBar);
    m_LifeProgress->setAnchorPoint(ccp(0,0));
    m_LifeProgress->setMidpoint(ccp(0.0f, 0.5f));
    playerFullBlood = m_PlayerFighterSprite->getBlood();
    m_LifeProgress->setBarChangeRate(ccp(1, 0));
    m_LifeProgress->setPosition(ccp(5,455));
    m_LifeProgress->setScale(0.5);
    m_LifeProgress->setPercentage(100);
}

void BattleActionLayer::initPauseButton()
{
    CCSprite *bt  = CCSprite::create();
    bt->initWithSpriteFrameName("pause.png");
    bt->setAnchorPoint(ccp(0,0));
    bt->setScale(0.5);
    bt->setOpacity(200);
    
    m_PauseButton = CCMenuItemImage::itemWithNormalSprite(bt, bt, this, menu_selector(BattleActionLayer::pauseCallback)); 
    
    m_PauseButtonMenu = CCMenu::menuWithItems(m_PauseButton, NULL); 
    m_PauseButtonMenu->setPosition(ccp(140, 470));
}

void BattleActionLayer::initPlayerFighter(int p_fighterID)
{
    FighterPrototypes* fighterPrototypes = FighterPrototypes::getInstance();
    Fighter *fighter = fighterPrototypes->getFighterByID(p_fighterID);
    
    //init player fighter sprite
    m_PlayerFighterSprite = PlayerFighterSprite::create();
    m_PlayerFighterSprite->initWithSpriteFrameName(fighter->getRes().c_str());
    m_PlayerFighterSprite->setFighterId(p_fighterID);
    m_PlayerFighterSprite->setBlood(fighter->getBlood());
    m_PlayerFighterSprite->setArmor(fighter->getArmor());
    m_PlayerFighterSprite->setSpeed(fighter->getSpeed());
    m_PlayerFighterSprite->setPosition(ccp(160,50));
    m_PlayerFighterSprite->setTag(kTagPlayerFighter);
    m_PlayerFighterSprite->setEntityType(PLAYER_FIGHTER);
    
    b2BodyDef playerBodyDef;
    playerBodyDef.type = b2_dynamicBody;
    CCPoint playerPostion = m_PlayerFighterSprite->getPosition();
    CCSize playerSize = m_PlayerFighterSprite->getContentSize();
    playerBodyDef.position = toMeters(playerPostion); //设置原点
    playerBodyDef.userData = m_PlayerFighterSprite;
    playerBodyDef.bullet = false;
    b2Body *playerBody = m_World->CreateBody(&playerBodyDef);
    playerBody->SetActive(true);
    
    b2PolygonShape playerDynamicBox;
    playerDynamicBox.SetAsBox(playerSize.width*0.15 / PTM_RATIO, playerSize.height*0.15 / PTM_RATIO,toMeters(CCPointZero),0);
    
    b2FixtureDef playerFixtureDef;
    playerFixtureDef.shape = &playerDynamicBox;
    playerFixtureDef.density = 0.0f;//密度
    playerFixtureDef.friction = 0.0f; //摩擦
    playerFixtureDef.restitution = 0.0f; //恢复
    playerFixtureDef.filter.groupIndex = FILTER_PLAYER_GROUPINDEX;
    playerFixtureDef.filter.categoryBits = FILTER_PLAYER_CATEGORYBITS;
    playerFixtureDef.filter.maskBits = FILTER_PLAYER_MASKBITS;
    playerBody->CreateFixture(&playerFixtureDef);
    m_PlayerFighterSprite->setPhysicsBody(playerBody);
    
    //init player bullet sprite
    CCArray *playerBullets = fighter->getBullets();
    CCObject *bullet = NULL;
    int bulletTypeTag = 1;
    CCARRAY_FOREACH(playerBullets, bullet)
    {
        CC_BREAK_IF(!bullet);
        int bulletBaseTag = (bulletTypeTag++)*10000;
        Bullet* mBullet = (Bullet*) bullet;
        int bulletID = mBullet->getID();
        const char *res = mBullet->getRes().c_str();
        int type = mBullet->getType();
        int damage = mBullet->getDamage();
        int frequency = mBullet->getFrequency();
        int speed = mBullet->getSpeed();
        float duration = mBullet->getDuration();
        int angle = mBullet->getAngle();
        int group_num = mBullet->getGroup_num();
        int group_interval = mBullet->getGroup_interval();
        int begin = mBullet->getBegin();
        BulletNode *bulletNode = new BulletNode();
        bulletNode->setGroup_num(group_num);
        bulletNode->setGroup_interval(group_interval);
        bulletNode->setFrequency(frequency);
        bulletNode->setBaseTag(bulletBaseTag);
        
        //计算最多可以产生多少个子弹
        float total_length = sqrt(pow(screenSize.width,2) + pow(screenSize.height,2));
        int maxBulletNum = ceil((total_length/speed)/frequency);
        bulletNode->setBulletCount(maxBulletNum);
        
        for(int i = 0;i < maxBulletNum;i++)
        {
            BulletSprite *bulletSprite = BulletSprite::create();
            
            bulletSprite->setID(bulletID);
            bulletSprite->initWithSpriteFrameName(res);
            bulletSprite->setType(type);
            bulletSprite->setDamage(damage);
            bulletSprite->setFrequency(frequency);
            bulletSprite->setSpeed(speed);
            bulletSprite->setDuration(duration);
            bulletSprite->setAngle(angle);
            bulletSprite->setGroup_num(group_num);
            bulletSprite->setBegin(begin);
            bulletSprite->setFirePoint((mBullet->getFirePoint()).x,(mBullet->getFirePoint()).y);
            bulletSprite->setScale(0.7);
            bulletSprite->setEntityType(PLAYER_BULLET);
            
            bulletNode->addBullets(bulletSprite);
            //bulletSprite->release();
        }
        m_PlayerFighterSprite->setBullets(bulletID, bulletNode);
    }
}

void BattleActionLayer::onEnter()
{
    CCLayer::onEnter();
    
    parent = (CCScene*)(this->getParent()->getParent());
    CCArray *bonusKeys = BonusPrototypes::getInstance()->bonusPrototype_Dict->allKeys();
    CCObject *bonusid_tmp = NULL;
    CCARRAY_FOREACH(bonusKeys, bonusid_tmp)
    {
        CCInteger *bonusid = static_cast<CCInteger*>(bonusid_tmp);
        bonusDict->setObject(CCInteger::create(0),bonusid->getValue());
    }
    
#ifndef BOXTEST    
    this->addChild(rearGround);
    this->addChild(rearGroundRe);
    this->addChild(frontGround);
    this->addChild(frontGroundRe);
#endif
    
    addChild(m_LifeBarBack);
    addChild(m_LifeProgress);
    addChild(m_PauseButtonMenu);
    this->addChild(m_SpriteBatch, 0, kTagPlayerFighterNode);
    m_SpriteBatch->addChild(m_PlayerFighterSprite, PLAYER_DEPTH,m_PlayerFighterSprite->getTag());
    
    CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(BattleActionLayer::changeProfile), CHANGE_PROFILE_NOTIFICATION, NULL);
    CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(BattleActionLayer::enemyExplosion), ENEMY_EXPLOSION_NOTIFICATION, NULL);
    CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(BattleActionLayer::playerExplosion), PLAYER_EXPLOSION_NOTIFICATION, NULL);
    CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(BattleActionLayer::destroyBullet), DESTROY_BULLET_NOTIFICATION, NULL);
    CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(BattleActionLayer::destroyBonus), DESTROY_BONUS_NOTIFICATION, NULL);
    CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(BattleActionLayer::payoff), PAYOFF_SCENEN_NOTIFICATION, NULL);
    CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(BattleActionLayer::playerBulletExplosion), PLAYERBULLET_EXPLOSION_ANIMATION_NOTIFICATION, NULL);
    setTouchEnabled(true);
    scheduleUpdate();
}

void BattleActionLayer::onExit()
{
    CCLayer::onExit();
   
    CC_SAFE_DELETE(bonusDict);
    if(this->isTouchEnabled())
    {
        this->setTouchEnabled(false);
    }
}

void BattleActionLayer::update(float dt)
{
    //background move
#ifndef BOXTEST
    frontGround->setPositionY(frontGround->getPositionY() + frontGround_rollingSpeed * dt);  
    if (frontGround->getPositionY() < -480) {  //暂时写死高度
        frontGround->setPositionY(frontGround->getPositionY() + 480 * 2 - 2);  
    }
    frontGroundRe->setPositionY(frontGroundRe->getPositionY() + frontGround_rollingSpeed * dt);  
    if (frontGroundRe->getPositionY() < -480) {  //暂时写死高度
        frontGroundRe->setPositionY(frontGroundRe->getPositionY() + 480 * 2 - 2);  
    }
    
    rearGround->setPositionY(rearGround->getPositionY() + rearGround_rollingSpeed * dt);  
    if (rearGround->getPositionY() < -480) {  //暂时写死高度
        rearGround->setPositionY(rearGround->getPositionY() + 480 * 2 - 2);  
    }
    rearGroundRe->setPositionY(rearGroundRe->getPositionY() + rearGround_rollingSpeed * dt);  
    if (rearGroundRe->getPositionY() < -480) {  //暂时写死高度
        rearGroundRe->setPositionY(rearGroundRe->getPositionY() + 480 * 2 - 2);  
    } 
#endif

    //enemyfighter appears
    m_iElapseFrame++;
    TracePrototypes *traceprototypes = TracePrototypes::getInstance();
    CCArray *startEnemies = stage->getStartEnemyIDs(m_iElapseFrame);
    CCObject *startEnemyObject = NULL;
    CCARRAY_FOREACH(startEnemies, startEnemyObject)
    {
        StageEnemy *stageEnemy = (StageEnemy*)startEnemyObject;
        Enemy *enemy = EnemyPrototypes::getInstance()->getEnemyByID(stageEnemy->getEnemyID());
        EnemyFighterSprite *enemyFighterSprite = new EnemyFighterSprite(m_PlayerFighterSprite);
        enemyFighterSprite->init();
        enemyFighterSprite->initWithSpriteFrameName(enemy->getRes().c_str());
        enemyFighterSprite->setFighterId(enemy->getFighterId());
        enemyFighterSprite->setBlood(enemy->getBlood());
        enemyFighterSprite->setArmor(enemy->getArmor());
        enemyFighterSprite->setTraceID(stageEnemy->getTraceID());
        enemyFighterSprite->setBonusID(stageEnemy->getBonusID());
        enemyFighterSprite->setTag(stageEnemy->getEnemyTag());
        enemyFighterSprite->setEnterPos((stageEnemy->getEnterPos()).x,(stageEnemy->getEnterPos()).y);
        enemyFighterSprite->setEntityType(ENEMY_FIGHTER);
        enemyFighterSprite->setPosition(enemyFighterSprite->getEnterPos());
        enemyFighterSprite->setIsBoss(stageEnemy->getIsBoss());
        
        m_SpriteBatch->addChild(enemyFighterSprite, ENEMY_DEPTH, enemyFighterSprite->getTag());
        
        b2BodyDef enemyFighterBodyDef;
        enemyFighterBodyDef.type = b2_dynamicBody;
        enemyFighterBodyDef.position = toMeters(enemyFighterSprite->getPosition());
        enemyFighterBodyDef.userData = enemyFighterSprite;
        b2Body *enemyFighterBody = m_World->CreateBody(&enemyFighterBodyDef);
        CCSize enemySize = enemyFighterSprite->getContentSize();
        b2PolygonShape enemyFighterDynamicBox;
        enemyFighterDynamicBox.SetAsBox(enemySize.width*0.5 / PTM_RATIO, enemySize.height*0.5 / PTM_RATIO,toMeters(CCPointZero),0);
        b2FixtureDef enemyFighterFixtureDef;
        enemyFighterFixtureDef.shape = &enemyFighterDynamicBox;
        enemyFighterFixtureDef.density = 0.0f;
        enemyFighterFixtureDef.friction = 0.0f;
        enemyFighterFixtureDef.filter.groupIndex = FILTER_ENEMY_GROUPINDEX;
        enemyFighterFixtureDef.filter.categoryBits = FILTER_ENEMY_CATEGORYBITS;
        enemyFighterFixtureDef.filter.maskBits = FILTER_ENEMY_MASKBITS;
        enemyFighterBody->CreateFixture(&enemyFighterFixtureDef);
        enemyFighterSprite->setPhysicsBody(enemyFighterBody);
        
        Trace *trace = traceprototypes->getTraceByID(enemyFighterSprite->getTraceID());
        if (NULL != trace)
        {
            CCArray *moves = trace->getMoves();
            CCObject *moveObject = NULL;
            CCArray *actions = CCArray::create();
            CCARRAY_FOREACH(moves, moveObject)
            {
                Move *move = (Move*)moveObject;
                int moveType = move->getMoveType();
                switch (moveType)
                {
                    case MOVE_MOVEBY:
                    {
                        CCActionInterval* action = FighterMoveByAction::create(move);
                        actions->addObject(action);
                        break;
                    }
                    case MOVE_BEZIERTWOBY:
                    {
                        CCActionInterval* action = FighterMoveBezierTwoByAction::create(move);
                        actions->addObject(action);
                        break;
                    }
                    case MOVE_BEZIERTHREEBY:
                    {
                        CCActionInterval* action = FighterMoveBezierThreeByAction::create(move);
                        actions->addObject(action);
                        break;
                    }
                    default:
                        break;
                }
            }
            
            actions->addObject(CCCallFuncND::create(this, callfuncND_selector(BattleActionLayer::destroyEnemyFighter), enemyFighterSprite));//所有动作完成后的销毁动作
            enemyFighterSprite->runAction(CCSequence::create(actions));  
        }
    }
    
    //collision test
    int velocityIterations = 2;
    int positionIterations = 1;
    //if (m_iElapseFrame % 2 == 0) {
        m_World->Step(dt, velocityIterations, positionIterations);
    //}

    for(b2Body *b = m_World->GetBodyList(); b; b=b->GetNext()) 
    {
        if (b->IsActive () && b->GetUserData() != NULL ) 
        {
            CCSprite *sprite = (CCSprite*)b->GetUserData();
            b2Vec2 b2Position = b2Vec2(sprite->getPositionX()/PTM_RATIO,
                                       sprite->getPositionY()/PTM_RATIO);
            float32 b2Angle = -1 * CC_DEGREES_TO_RADIANS(sprite->getRotation());
            b->SetTransform(b2Position, b2Angle);
        }
    }
    
}

void BattleActionLayer::draw()
{
    //return;
    CCLayer::draw();
    ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position );
    kmGLPushMatrix();
    m_World->DrawDebugData();
    kmGLPopMatrix(); 
}

void BattleActionLayer::ccTouchesBegan(CCSet* touches, CCEvent* event) 
{
    m_PlayerFighterSprite->touchesBegan(touches, event);
}

void BattleActionLayer::ccTouchesMoved(CCSet* touches, CCEvent* event) 
{
    m_PlayerFighterSprite->touchesMoved(touches, event);
}

void BattleActionLayer::ccTouchesEnded(CCSet *touches, CCEvent *event)
{
    m_PlayerFighterSprite->touchesEnded(touches, event);
}

void BattleActionLayer::pauseCallback()
{
    CCDirector::sharedDirector()->pause();
    MsgBoxLayer *msgBox = MsgBoxLayer::node();
    msgBox->initDialog("返回主菜单？", menu_selector(BattleActionLayer::clickBack), menu_selector(BattleActionLayer::clickContinue));
    addChild(msgBox);
}

void BattleActionLayer::clickBack()
{
    CCDirector::sharedDirector()->resume();
    CCScene *pScene = CCScene::create();
    CCLayer *pLayer = MenuLayer::create();
    pScene->addChild(pLayer);
    CCDirector::sharedDirector()->replaceScene(pScene);
}

void BattleActionLayer::clickContinue()
{
    removeFromParentAndCleanup(true);
    CCDirector::sharedDirector()->resume();
}

void BattleActionLayer::changeProfile(CCInteger* blood)
{
    BattleActionLayer::getInstance()->m_LifeProgress->setPercentage((float)blood->getValue()/playerFullBlood*100);
}

void BattleActionLayer::enemyExplosion(CCInteger* tag)
{
    EnemyFighterSprite* enemySprite = (EnemyFighterSprite*)BattleActionLayer::getInstance()->m_SpriteBatch->getChildByTag(tag->getValue());
    CCSprite *ani = enemyExplosionAnimation("", 22, 0.02, enemySprite->getPosition());
    BattleActionLayer::getInstance()->addChild(ani, FIGHTEREXPLOSION_DEPTH);
    if (enemySprite->getIsBoss() == 1) {

        CCActionManager *actionManager = enemySprite->getActionManager();
        actionManager->removeAllActionsFromTarget(enemySprite);
        
        enemySprite->bulletDict->removeAllObjects ();
        enemySprite->setToDestroyFlag(ENEMY_DESTROY_BOSS);
        enemySprite->runAction(CCSequence::create(CCMoveTo::create(3, CCPointMake(enemySprite->getPositionX(),-100)),CCCallFuncND::create(BattleActionLayer::getInstance(), callfuncND_selector(BattleActionLayer::destroyEnemyFighter), enemySprite),NULL)); //暂时写死距离
    }
    else
    {
        enemySprite->setToDestroyFlag(ENEMY_DESTROY_DIE);
    }
}

void BattleActionLayer::playerExplosion(CCObject* obj)
{
    BattleActionLayer::getInstance()->m_LifeProgress->setPercentage(0.0f);
    CCSprite *ani = enemyExplosionAnimation("", 22, 0.02, BattleActionLayer::getInstance()->m_PlayerFighterSprite->getPosition());
    BattleActionLayer::getInstance()->addChild(ani, FIGHTEREXPLOSION_DEPTH);
    BattleActionLayer::getInstance()->m_PlayerFighterSprite->setToDestroyFlag(PLAYER_DESTROY_DIE);
    
}

void BattleActionLayer::playerBulletExplosion(CCInteger* tag)
{
    BulletSprite* bulletSprite = (BulletSprite*)BattleActionLayer::getInstance()->m_SpriteBatch->getChildByTag(tag->getValue());
    CCSprite *ani = playerBulletExplosionAnimation("", bulletSprite->getPosition());
    BattleActionLayer::getInstance()->addChild(ani, BULLETEXPLOSION_DEPTH);
}

/*
 销毁敌机子弹
 */
void BattleActionLayer::destroyBullet(CCDictionary* dict)
{
    CCInteger *tag = (CCInteger*)dict->objectForKey("tag");
    CCInteger *type = (CCInteger*)dict->objectForKey("type");
    EnemyBulletSprite* bullet = (EnemyBulletSprite*)BattleActionLayer::getInstance()->m_SpriteBatch->getChildByTag(tag->getValue());
    if(bullet->getToDestroyFlag() == 0){
        if(type->getValue() == ENEMYBULLET_DESTROY_COLLISION) // 碰撞销毁
        {
            bullet->setToDestroyFlag(ENEMYBULLET_DESTROY_COLLISION);
            //        CCSprite *ani = bulletExplosion("", bullet->getPosition());
            //        addChild(ani, BULLETEXPLOSION_DEPTH);
        }
        else
        {
             bullet->setToDestroyFlag(ENEMYBULLET_DESTROY_OUT);
        }
    }
}

/*
 销毁敌机
 */
void BattleActionLayer::destroyEnemyFighter(EnemyFighterSprite* enemy)
{
    enemy->setToDestroyFlag(ENEMY_DESTROY_OUT);
}

void BattleActionLayer::destroyBonus(CCDictionary* dict)
{
    CCInteger *tag = (CCInteger*)dict->objectForKey("tag");
    CCInteger *type = (CCInteger*)dict->objectForKey("type");
    BonusSprite* bonusSprite = (BonusSprite*)BattleActionLayer::getInstance()->m_SpriteBatch->getChildByTag(tag->getValue());
    if(type->getValue() == BONUS_DESTROY_COLLECT) // 碰撞销毁
    {
        //播放声音或动画
        CCInteger *bonus_num = (CCInteger*)BattleActionLayer::getInstance()->bonusDict->objectForKey(bonusSprite->getID());
        CCInteger *new_bonus_num = CCInteger::create(bonus_num->getValue()+1);
        BattleActionLayer::getInstance()->bonusDict->setObject(new_bonus_num, bonusSprite->getID());
        bonusSprite->setToDestroyFlag(BONUS_DESTROY_COLLECT);
    }
    else
    {
        bonusSprite->setToDestroyFlag(BONUS_DESTROY_OUT);
    }
}

CCSprite* BattleActionLayer::enemyExplosionAnimation(const char *name, int count, float delay, CCPoint pos)
{
    CCSpriteFrameCache *cache = CCSpriteFrameCache::sharedSpriteFrameCache();
    CCArray *animFrames = new CCArray(count);
    
    char str[80];
    for(int k = 0; k < count; k++) 
    {
        sprintf(str, "%s%d.png", name, k + 1);
        CCSpriteFrame *frame = cache->spriteFrameByName(str);
        animFrames->addObject(frame);
    }
    
    CCAnimation *animation = CCAnimation::animationWithSpriteFrames(animFrames, delay);
    CCSprite *sprite = CCSprite::spriteWithSpriteFrameName("1.png");
    sprite->setPosition(pos);
    
    CCFiniteTimeAction *actionND = CCSequence::actions(
                                                       CCAnimate::actionWithAnimation(animation),
                                                       CCCallFuncND::actionWithTarget(BattleActionLayer::getInstance(), callfuncND_selector(BattleActionLayer::actionCallbackND), (void*)"Callback Data"), NULL);
    sprite->runAction(actionND);
    
    return sprite;
}

CCSprite* BattleActionLayer::playerBulletExplosionAnimation(const char *name, CCPoint pos)
{
    CCSpriteFrameCache *cache = CCSpriteFrameCache::sharedSpriteFrameCache();
    CCArray *animFrames = new CCArray(1);

    CCSpriteFrame *frame = cache->spriteFrameByName("2.png");
    animFrames->addObject(frame);

    CCAnimation *animation = CCAnimation::animationWithSpriteFrames(animFrames, 0.02);
    CCSprite *sprite = CCSprite::spriteWithSpriteFrameName("2.png");
    sprite->setPosition(pos);

    CCFiniteTimeAction *actionND = CCSequence::actions(
                                                       CCAnimate::actionWithAnimation(animation),
                                                       CCCallFuncND::actionWithTarget(BattleActionLayer::getInstance(), callfuncND_selector(BattleActionLayer::actionCallbackND), (void*)"Callback Data"), NULL);
    sprite->runAction(actionND);
    sprite->setScale(0.5);

    return sprite;

}

void BattleActionLayer::actionCallbackND(CCNode *pSender, void *data)
{ 
    CCSprite *sprite = (CCSprite*)pSender; 
    removeChild(sprite, false);
}

void BattleActionLayer::payoff(CCInteger* type)
{
    CCDictionary *p_bonusDict = CCDictionary::create();
    CCDictElement* bonusElement = NULL;
    
    char bb[10];
    CCDictionary *dict = BattleActionLayer::getInstance()->bonusDict;
    CCDICT_FOREACH(dict, bonusElement)
    {
        int bonusid = bonusElement->getIntKey();
        CCInteger *value  = (CCInteger*)bonusElement->getObject();
        CCLog("bounid = %d value = %d",bonusid,value->getValue());
        sprintf(bb,"%d",value->getValue());
        p_bonusDict->setObject(new CCString(bb), bonusid);
    }
    
    CCScene *payOffScene = CCScene::create();
    CCLayer *payOffLayer = PayOffLayer::create(p_bonusDict);
    ((PayOffLayer*)payOffLayer)->setType((PayOff_type)type->getValue());
    payOffScene->addChild(payOffLayer,0);
    CCDirector::sharedDirector()->replaceScene( CCTransitionSplitRows::create(0.8f, payOffScene) );
}
